import marimo

__generated_with = "0.8.0"
app = marimo.App()


@app.cell
def __():
    # import os, re
    # import os, re, shutil
    import shutil, os, re, logging, sys
    import PyPDF2 as pp
    # import os, re
    import pandas as pd
    import py7zr, rarfile
    import os, zipfile
    return logging, os, pd, pp, py7zr, rarfile, re, shutil, sys, zipfile


@app.cell
def __(os):
    """
    shell 命令
    将flv转mp4
    """
    # import os, re
    _path = '/Volumes/public/tutorial_video/张飞/硬件设计与开发第07部'
    os.chdir(_path)
    for _f in os.listdir('.'):
        if _re.match('.*?flv', _f):
            f_a = _f.split('.')[0] + '.mp4'
            os.system(f'ffmpeg -i {_f} -c copy {f_a}')
    return f_a,


@app.cell
def __(os, shutil):
    '''
    将文件名中的.替换为_
    '''


    # import os, re, shutil
    _path = '/Users/earlshaw/Desktop/python_video'
    os.chdir(_path)
    _a_files = []
    for _f in os.listdir('.'):
        if _re.match('.*?avi', _f):
            # 将文件名（不包括扩展名）中的所有.替换为_
            f_1 = _re.sub('\\.', '_', _f[:-4])
            shutil.move(_f, f_1 + '.avi')
    return f_1,


@app.cell
def __(os):
    """
    特殊视频
    提取.avi中的音频，视频
    将视频转码
    打包入mp4
    """
    # import os, re
    _path = '/Users/earlshaw/Desktop/test'
    os.chdir(_path)
    _a_files = []
    for _f in os.listdir('.'):
        if _re.match('.*?avi', _f):
            _a_files.append(_f)
    _a_files.sort()
    _a_files
    for _f in _a_files:
        os.system(f"ffmpeg -i '{_f}' -vn -acodec copy aa.wav")
        os.system(f'ffmpeg -i aa.wav -acodec aac aa.aac')
        os.remove('aa.wav')
        os.system(f"ffmpeg -i '{_f}' -c:v copy -an aa.mp4")
        os.remove(_f)
        os.system(f"ffmpeg -i aa.mp4 -i aa.aac -c copy -map 0:v:0 -map 1:a:0 '{_f.split('.')[0] + '.mp4'}'")
        os.remove('aa.aac')
        os.remove('aa.mp4')
        print(f'{_f} done')
    return


@app.cell
def __(dirpath, os, shutil):
    """
    文件名依次向前错位
    批量重命名纠正
    """
    # import shutil
    for _root, _dirs, _files in os.walk(dirpath):
        files_n = _files.copy()
        files_n.insert(0, 'aa')
        del files_n[-1]
        print(_files, len(_files))
        print(files_n, len(files_n))
        _i = 0
        for _file in _files:
            shutil.move(os.path.join(_root, _file), os.path.join(_root, files_n[_i]))
            _i = _i + 1
        print('done')
    return files_n,


@app.cell
def __(logging, os, shutil):
    """
    漫画重命名
    使用正则，将文件名拆分，重组
    """
    # import shutil, os, re, logging
    logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
    logging.disable(logging.CRITICAL)
    os.chdir('g:/教头当家 - Copy')
    txt_p = _re.compile('^(\\d{3})_          # 开头3位数字\n                    ((0|1|2)?\\d)卷        # 中间2位数字，第一位为0或1或2或3\n                    (.*?)$                 # 结尾\n                    ', _re.VERBOSE)
    logging.debug(os.listdir('.'))
    for _f_name in os.listdir('.'):
        mo = txt_p.search(_f_name)
        logging.debug(mo)
        logging.debug(mo.group(1))
        logging.debug(mo.group(2))
        logging.debug(mo.group(3))
        logging.debug(mo.group(4))
        if mo == None:
            continue
        pre_p = '教头当家_vol'
        m_p = mo.group(2)
        sub_p = mo.group(4)
        f_new = f'{pre_p}{m_p}{sub_p}'
        abs_dir = os.path.abspath('.')
        amer_f = os.path.join(abs_dir, _f_name)
        euro_f = os.path.join(abs_dir, f_new)
        logging.debug(f'rename {amer_f} to {euro_f}...')
        shutil.move(amer_f, euro_f)
    return abs_dir, amer_f, euro_f, f_new, m_p, mo, pre_p, sub_p, txt_p


@app.cell
def __(os):
    '''
    列出文件夹中的所有文件
    '''


    # import re, os, sys
    _path = '/Users/earlshaw/Desktop/fc/fc roms/fc'
    os.chdir(_path)
    for _root, _dirs, _files in os.walk(_path):
        print(_files)
    return


@app.cell
def __(os):
    '''
    将后缀名mp41，重命名为mp4
    '''

    # import os, re
    _path = '/Volumes/Untitled/魔神英雄传1080P修复'
    os.chdir(_path)
    _pdf_files = []
    for _f in os.listdir('.'):
        if _re.match('.*mp41', _f):
            _pdf_files.append(_f)
    _pdf_files.sort(key=str.lower)
    print(_pdf_files)
    print(len(_pdf_files))
    for _f_name in _pdf_files:
        _root, ext = os.path.splitext(_f_name)
        new_file_name = _root + '.mp4'
        os.rename(_f_name, new_file_name)
    print('done!')
    return ext, new_file_name


@app.cell
def __(os):
    '''
    解压文件夹中的所有zip，每100个打印一次
    '''



    # import os, re
    _path = '/Users/earlshaw/Downloads/sfc_rom'
    os.chdir(_path)
    _i = 0
    for _f in os.listdir('.'):
        if _re.match('.*zip', _f):
            os.system(f'unzip "{_f}" -d .')
            _i = _i + 1
        if _i % 100 == 0:
            print(f'{_i} done!')
    return


@app.cell
def __(os, shutil):
    '''
    将目录及其子目录中的.mp4移动到，最外面的目录中
    '''



    # import os, re, shutil
    _path = 'D:/vitrual_share/直播课32个python项目'
    os.chdir(_path)
    for _root, _dirs, _files in os.walk(_path):
        for _f in _files:
            if _re.match('.*\\(1\\).mp4', _f):
                _a = _root + os.sep + _f
                shutil.move(_a, '.')
    return


@app.cell
def __(os, shutil):
    '''
    将目录及其子目录中的.zip移动到，最外面的目录中
    '''

    # import os, re, shutil
    _path = '/Users/earlshaw/Downloads/gba'
    _re_part = '.*zip'
    os.chdir(_path)
    _i = 0
    for _root, _dirs, _files in os.walk(_path):
        for _f in _files:
            if _re.match(_re_part, _f):
                _a = _root + os.sep + _f
                shutil.move(_a, '.')
    return


@app.cell
def __(os, shutil):
    '''
    将目录及其子目录中的.nes移动到，最外面的目录中
    '''


    # import os, re, shutil
    _path = '/Users/earlshaw/Downloads/fc'
    _re_part = '.*nes'
    os.chdir(_path)
    for _root, _dirs, _files in os.walk(_path):
        for _f in _files:
            
            if _re.match(_re_part, _f):
                # 如果当前目录中有.nes文件则跳过
                if os.path.exists(_f):
                    continue
                # 否则，文件在子目录中，将它移动到当前目录
                else:
                    _a = _root + os.sep + _f
                    shutil.move(_a, '.')
    return


@app.cell
def __(os, shutil):
    '''
    将mp4移动到目前所在文件夹
    '''

    # import os, re, shutil
    _path = 'D:/vitrual_share/直播课32个python项目'
    os.chdir(_path)
    for _root, _dirs, _files in os.walk(_path):
        for _f in _files:
            if _re.match('.*.mp4', _f):
                _a = _root + os.sep + _f
                shutil.move(_a, '.')
    return


@app.cell
def __(os):
    '''
    列出所有mp4的完整路径
    '''

    # import os, re, shutil
    _path = 'D:/vitrual_share/python_70'
    os.chdir(_path)
    for _root, _dirs, _files in os.walk(_path):
        for _f in _files:
            if _re.match('.*.mp4', _f):
                _a = _root + os.sep + _f
                print(_a)
    return


@app.cell
def __(os, shutil):
    '''
    批量重命名文件夹内的mp4，貌似有问题
    '''


    # import os, re
    _path = '/Volumes/public/aa/张飞/硬件设计与开发第05部'
    os.chdir(_path)
    cha = '_5-'
    mp4_files = []
    for _f in os.listdir('.'):
        if _re.match('.*?mp4', _f):
            mp4_files.append(_f)
    for _f in mp4_files:
        if _re.match('^\\d_', _f[13:]):
            _g = _f[:13] + '0' + _f[13:]
            mp4_files.remove(_f)
            mp4_files.append(_g)
    for _f in mp4_files:
        if _re.match('^\\d_', _f[13:]):
            _g = _f[:13] + '0' + _f[13:]
            mp4_files.remove(_f)
            mp4_files.append(_g)
    mp4_files.sort()
    mp4_files
    for _f in mp4_files:
        _b = mp4_files.index(_f) + 1
        _a = 'lesson' + cha + str(_b) + '.mp4'
        print(_a)
        shutil.move(_f, _a)
    return cha, mp4_files


@app.cell
def __(os):
    '''
    列出.avi文件
    '''

    # import os, re, shutil
    _path = '/Volumes/public/aa/python视频/python_3'
    os.chdir(_path)
    _a_files = []
    for _f in os.listdir('.'):
        if _re.match('.*avi', _f):
            _a_files.append(_f)
    _a_files
    return


@app.cell
def __(os):
    '''
    将.sfc文件名写入txt文档
    '''

    # import os, re
    _path = '/Users/earlshaw/Downloads/roms/sfc_rom'
    _re_part = '.*(bin|sfc)'
    os.chdir(_path)
    _a_files = []
    with open('index.txt', 'w') as _f:
        for _g in os.listdir('.'):
            if _re.match(_re_part, _g):
                _a_files.append(_g)
        _a_files.sort()
    with open('index.txt', 'w') as _f:
        for _i in range(len(_a_files)):
            _f.writelines(_a_files[_i] + '\n')
    return


@app.cell
def __(
    destination_folder,
    os,
    py7zr,
    rarfile,
    shutil,
    source_folder,
    zipfile,
):
    """
    解压目录内的7z，rar，zip等文件
    """
    # import os, py7zr, shutil, rarfile
    _folder_path = 'path_to_folder'
    if not os.path.exists(destination_folder):
        os.makedirs(destination_folder)
    _files = os.listdir(_folder_path)
    for _file in _files:
        if _file.endswith('.rar'):
            rf = rarfile.RarFile(os.path.join(_folder_path, _file))
            rf.extractall(path='path_to_extract_folder')
            rf.close()
            source_file = os.path.join(source_folder, _file)
            destination_file = os.path.join(destination_folder, _file)
            shutil.move(source_file, destination_file)
        elif _file.endswith('.7z'):
            archive = py7zr.SevenZipFile(os.path.join(_folder_path, _file), mode='r')
            archive.extractall(path='path_to_extract_folder')
            archive.close()
            source_file = os.path.join(source_folder, _file)
            destination_file = os.path.join(destination_folder, _file)
            shutil.move(source_file, destination_file)
        elif _file.endswith('.zip'):
            with zipfile.ZipFile(os.path.join(_folder_path, _file), 'r') as zip_ref:
                zip_ref.extractall(path='path_to_extract_folder')
            source_file = os.path.join(source_folder, _file)
            destination_file = os.path.join(destination_folder, _file)
            shutil.move(source_file, destination_file)
    print('解压完成')
    return archive, destination_file, rf, source_file, zip_ref


@app.cell
def __(os, zipfile):
    """
    目录内文件夹转为zip
    """
    # import os, zipfile

    class FolderZipper:

        def __init__(self, folder_path):
            self.folder_path = _folder_path

        def zip_folder(self, folder_path):
            zip_path = f'{_folder_path}.zip'
            with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
                for _root, _, _files in os.walk(_folder_path):
                    for _file in _files:
                        file_path = os.path.join(_root, _file)
                        archive_name = os.path.relpath(file_path, self.folder_path)
                        zipf.write(file_path, archive_name)
            print(f'{zip_path}压缩完成')

        def compress_folders_in_directory(self):
            for _root, _dirs, _ in os.walk(self.folder_path):
                for dir_name in _dirs:
                    _folder_path = os.path.join(_root, dir_name)
                    self.zip_folder(_folder_path)
    directory_path = '/Users/earlshaw/Downloads/漫画'
    folder_zipper = FolderZipper(directory_path)
    folder_zipper.compress_folders_in_directory()
    return FolderZipper, directory_path, folder_zipper


@app.cell
def __(os):
    """
    将文件夹中的子文件夹名写入文档
    """
    # import os
    _folder_path = '/Volumes/comic/download'
    subfolders = [_f.name for _f in os.scandir(_folder_path) if _f.is_dir()]
    output_file = 'output.txt'
    with open(output_file, 'w') as _file:
        for subfolder in subfolders:
            _file.write(subfolder + '\n')
    print('子文件夹名已写入文档:', output_file)
    return output_file, subfolder, subfolders


if __name__ == "__main__":
    app.run()
